/* 
 *
 */
package com.cory.admin.sys.controller.admin;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beust.jcommander.internal.Maps;
import com.cory.admin.sys.controller.AdminController;
import com.cory.admin.sys.domain.entity.SysResource;
import com.cory.admin.sys.domain.entity.SysRole;
import com.cory.admin.sys.enums.EResourceType;
import com.cory.admin.sys.service.SysResourceService;
import com.cory.admin.sys.service.SysRoleResourceService;
import com.cory.admin.sys.service.SysRoleService;
import com.cory.boot.domain.bean.Result;
import com.cory.boot.domain.enumdef.EState;
import com.cory.module.oplog.core.OpLogClient;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;

/**
 * 角色管理
 * @author xiongcong
 * @date 2020-02-04
 */
@Controller
@RequestMapping("admin/sys/role")
public class SysRoleController extends AdminController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysResourceService sysResourceService;
    @Autowired
    private SysRoleResourceService sysRoleResourceService;
    
    @RequestMapping("list")
    public String list(SysRole param, Model model) {
        param.setTenantId(super.getTenantId());
        param.setUserType(super.getPrincipal().getUserType());
        
        super.startPage();
        List<SysRole> list = sysRoleService.list(param);
        
        model.addAttribute("page", new PageInfo<>(list));
        model.addAttribute("param", param);
        return "admin/sys/role/list";
    }
    
    @RequestMapping("form")
    public String form(Integer id, Model model) {
        if (id != null) {
            model.addAttribute("info", sysRoleService.getById(id));
        }
        return "admin/sys/role/form";
    }
    
    @RequestMapping("save")
    @ResponseBody
    public Result<?> save(SysRole info) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.ne("state", EState.DELETE.key).eq("name", info.getName()).eq("tenant_id", super.getTenantId());
        
        SysRole tmp = sysRoleService.getOne(wrapper);
        if (tmp != null && (info.getId() == null || !info.getId().equals(tmp.getId()))) {
            return Result.fail("角色名称已存在");
        }
        
        if (info.getId() == null) {
            info.setTenantId(super.getTenantId());
            info.setUserType(super.getPrincipal().getUserType());
            sysRoleService.save2Log(info);
        } else {
            sysRoleService.updateById2Log(info);
        }
        
        return Result.success("保存成功");
    }
    
    @RequestMapping("delete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(Integer id, String ids) {
        List<Integer> idList = id != null ? Lists.newArrayList(id) : 
            Arrays.asList(ids.split(",")).stream().filter(item -> StringUtils.isNotBlank(item))
            .map(item -> Integer.valueOf(item)).collect(Collectors.toList());
        
        if (idList.size() > 0) {
            sysRoleService.deleteByIds2Log(idList);
        }
        
        return Result.success((idList.size() > 1 ? "批量" : "") + "删除成功");
    }
    
    @RequestMapping("updateState")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateState(Integer id, String ids, Integer state) {
        List<Integer> idList = id != null ? Lists.newArrayList(id) : 
            Arrays.asList(ids.split(",")).stream().filter(item -> StringUtils.isNotBlank(item))
            .map(item -> Integer.valueOf(item)).collect(Collectors.toList());
        
        if (idList.size() > 0) {
            sysRoleService.updateStateByIds2Log(idList, state);
        }
        
        return Result.success((idList.size() > 1 ? "批量" : "") + (state == 1 ? "启用" : "禁用") + "成功");
    }
    
    @GetMapping("resource")
    public String resource(Integer id, Model model) {
        SysRole info = sysRoleService.getById(id);
        model.addAttribute("info", info);
        model.addAttribute("roleResourceIds", sysRoleResourceService.selectRoleResourceIds(id));
        
        List<SysResource> resources = sysResourceService.selectResourceByType(info.getUserType());
        List<SysResource> resources_1 = resources.stream().filter(i -> i.getType() == EResourceType.SERVICE.key).collect(Collectors.toList());
        List<SysResource> resources_2 = resources.stream().filter(i -> i.getType() == EResourceType.FOLDER.key).collect(Collectors.toList());
        List<SysResource> resources_3 = resources.stream().filter(i -> i.getType() == EResourceType.MENU.key).collect(Collectors.toList());
//        List<SysResource> resources_4 = resources.stream().filter(i -> i.getType() == EResourceType.BUTTON.key).collect(Collectors.toList());
        
        Map<String, Integer> resources_1_rows_map = Maps.newHashMap();
        
        Map<String, List<SysResource>> resources_2_map = Maps.newHashMap();
        for (SysResource resource_1 : resources_1) {
            List<SysResource> resource_2 = resources.stream().filter(i -> resource_1.getId().equals(i.getPid())).collect(Collectors.toList());
            resources_2_map.put(resource_1.getId() + "", resource_2);
        }
        
        Map<String, List<SysResource>> resources_3_map = Maps.newHashMap();
        for (SysResource resource_2 : resources_2) {
            List<SysResource> resource_3 = resources.stream().filter(i -> resource_2.getId().equals(i.getPid())).collect(Collectors.toList());
            resources_3_map.put(resource_2.getId() + "", resource_3);
            
            if (!resources_1_rows_map.containsKey(resource_2.getPid() + "")) {
                resources_1_rows_map.put(resource_2.getPid() + "", 0);
            }
            resources_1_rows_map.put(resource_2.getPid() + "", resources_1_rows_map.get(resource_2.getPid() + "") + resource_3.size());
        }
        
        Map<String, List<SysResource>> resources_4_map = Maps.newHashMap();
        for (SysResource resource_3 : resources_3) {
            List<SysResource> resource_4 = resources.stream().filter(i -> resource_3.getId().equals(i.getPid())).collect(Collectors.toList());
            resources_4_map.put(resource_3.getId() + "", resource_4);
        }
        
        model.addAttribute("resources_1", resources_1);
        model.addAttribute("resources_2_map", resources_2_map);
        model.addAttribute("resources_3_map", resources_3_map);
        model.addAttribute("resources_4_map", resources_4_map);
        model.addAttribute("resources_1_rows_map", resources_1_rows_map);
        return "admin/sys/role/resource";
    }
    
    @PostMapping("saveResource")
    @ResponseBody
    public Result<?> saveResource(HttpSession session, Integer id, String resourceIds) {
        assertNotNull(id);
        resourceIds = StringUtils.defaultIfBlank(resourceIds, "");
        List<Integer> resourceIdList = Stream.of(resourceIds.split(",")).filter(i -> StringUtils.isNotBlank(i))
                .map(i -> Integer.valueOf(i)).collect(Collectors.toList());
        
        sysRoleResourceService.saveRoleResources(id, resourceIdList);
        OpLogClient.addLog(SysRole.class, id, "分配权限");
        return Result.success("保存成功");
    }
}
